//
//  SYDNetTool.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/19.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDNetTool.h"

@implementation SYDNetTool
// 处理字典参数
+ (NSString *)dealWithParam:(NSDictionary *)param
{
    NSArray *allkeys = [param allKeys];
    
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys) {
        
        NSString *str = [NSString stringWithFormat:@"%@=%@&",key,param[key]];
        
        [result appendString:str];
    }
    
    return [result substringWithRange:NSMakeRange(0, result.length-1)];
    
}

// 自带原生的get请求方式
+ (void)getRequestByServiceUrl:(NSString *)service
                        andApi:(NSString *)api
                     andParams:(NSDictionary *)params
                   andCallBack:(void (^)(id obj))callback
{
    NSString *basePath = [[service stringByAppendingString:api ? api : @""] stringByAppendingString:@"?"];
    
    NSString *urlString = nil;
    // 因为参数是以字典的形式传进来的，所以用了一个 dealWithParam 方法拼接参数。
    if (params) {
        NSString *paramStr =  [self dealWithParam:params];
        urlString = [basePath stringByAppendingString:paramStr];
    }else
    {
        urlString = basePath;
    }
    
    NSString *pathStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:pathStr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    request.timeoutInterval = 200;
    
    NSLog(@"---通知设备推流---%@",pathStr);
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse * res = (NSHTTPURLResponse *)response;
            if (res.statusCode == 200) {
                NSLog(@"获取推流成功");
            }
        }
        
        NSLog(@"--response--%@",response);
        
        if (!response) {
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (dic) {
                callback(dic);
            }else
            {
                
                callback(error.description);
            }
            
        });
        
    }];
    
    [task resume];
    
}

// 自带原生post请求

+ (void)postRequestByServiceUrl:(NSString *)service
                         andApi:(NSString *)api
                      andParams:(NSDictionary *)params
                    andCallBack:(void (^)(id obj))callback
{
    
    // 创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSString *basePath = [service stringByAppendingString:api ? api : @""];
    
    NSURL *url = [NSURL URLWithString:basePath];
    
    // 创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 修改请求方法为POST
    [request setHTTPMethod:@"POST"];
    
    // 设置请求体
    [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];
    
    //    // 设置本次请求的提交数据格式
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //
    //    // 设置本次请求请求体的长度(因为服务器会根据你这个设定的长度去解析你的请求体中的参数内容)
    //    [request setValue:[NSString stringWithFormat:@"%ld",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    
    // 设置本次请求的最长时间
    request.timeoutInterval = 10;
    
    // 根据会话对象创建一个Task(发送请求）
    /*
     第一个参数：请求对象
     第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
     data：响应体信息（期望的数据）
     response：响应头信息，主要是对服务器端的描述
     error：错误信息，如果请求失败，则error有值
     */
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        [SVProgressHUD hide];
        
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSDictionary * dic = [self parseJsonStringToNSDictionary:responseString];
        
        if (dic) {
            callback(dic);
        }else
        {
            //            callback(error.description);
        }
        
    }];
    
    [task resume];
    
    [SVProgressHUD displayWithStatus:@""];
    
}

+ (void)request:(NSString*)httpUrl withHttpArg:(NSDictionary*)parameters callBack:(void(^)(id responseObject))callback{
    NSURL *url = [NSURL URLWithString: httpUrl];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 30];
    [request setHTTPMethod: @"POST"];
    if (parameters) {
        if (![request valueForHTTPHeaderField:@"Content-Type"]) {
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil]];
    }
    [SVProgressHUD displayWithStatus:@""];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               [SVProgressHUD hide];
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                                   [SVProgressHUD displayErrorWithStatus:error.localizedDescription];
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   //                                   NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                   
                                   NSDictionary *dicjson = [self parseJsonStringToNSDictionary:responseString];
                                   NSLog(@"----Post---%@",dicjson);
                                   callback(dicjson);
                               }
                           }];
}

// 原生上传图片
+ (void) postImageWithBaseApi:(NSString *)baseApi AndPragram:(NSDictionary *)pragram updatImage:(UIImage *)image Completion:(void (^) (id obj))completion
{
    
    if (!image) {
        return;
    }
    
    NSString *sep = @"ABFC134";
    
    // 1、创建ULR
    NSURL *url = [NSURL URLWithString:baseApi];
    
    // 2、创建Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 3、设置相关属性
    
    // 3.1、设置请求方式
    [request setHTTPMethod:@"POST"];
    
    // 3.2处理基本参数(不含图片)
    
    NSArray *allKeys = [pragram allKeys];
    
    NSMutableString *bodyString = [NSMutableString string];
    
    for (NSString *key in allKeys)
    {
        [bodyString appendFormat:@"--%@\r\n",sep];
        
        NSString *temStr = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",key,pragram[key]];
        [bodyString appendString:temStr];
        //        NSLog(@"%@",bodyString);
        
    }
    
    // 3.3、拼上图片
    [bodyString appendFormat:@"--%@\r\n",sep];
    
    NSString *imageDes = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n"];
    [bodyString appendString:imageDes];
    
    
    NSString *imageType = [NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"];
    [bodyString appendString:imageType];
    
    // 3.4、将图片转换成二进制
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    
    // 3.5、往bodyString中加入图片
    // 3.5.1、先将bodyString转成二进制
    NSMutableData *bodyData = [NSMutableData dataWithData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [bodyData appendData:imageData];
    
    // 4、追加结束标示
    NSString *end = [NSString stringWithFormat:@"\r\n--%@--",sep];
    [bodyData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    // 5、设置请求体
    [request setHTTPBody:bodyData];
    
    // 6、设置request的value中content－type
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",sep] forHTTPHeaderField:@"Content-Type"];
    
    // 7、设置请求体的长度
    [request setValue:[NSString stringWithFormat:@"%ld",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    
    // 8、设置超时
    [request setTimeoutInterval:30.0f];
    
    // 9、发出请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (dic) {
            completion(dic);
        }else
        {
            
            completion(connectionError.description);
            
        }
    }];
}


/**
 去除制表符
 
 @param jsonString json字符串
 @return json字典
 */
+ (NSDictionary *)parseJsonStringToNSDictionary:(NSString *)jsonString
{
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    
    NSError *error = nil;
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
    
    if (dict) {
        return dict;
    }
    return nil;
}

@end
